#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <time.h>
#include "logger.h"
#include "gettemp.h"

#define PATH "/sys/bus/w1/devices/"

int get_temperature(float *temp)
{
	int 		        fd=-1;
	int					rv=1;
	char 		        buf[128];
	char	       	    *str=NULL;
	DIR	               	*dirp=NULL;	
	struct dirent       *dirrep=NULL;
	int					found=0;
	char				w1_path[128]=PATH;

	dirp = opendir(PATH);
	if(!dirp)
	{
		log_error("dir %s : %s",PATH,strerror(errno));
		return -1;
	}

	while(NULL != (dirrep = readdir(dirp)))
	{
		if(strstr(dirrep->d_name,"28-"))
		{	
			found = 1;
			strncat(w1_path,dirrep->d_name,sizeof(w1_path)-strlen(w1_path));
			strncat(w1_path,"/w1_slave",sizeof(w1_path)-strlen(w1_path));
		}
	}
	closedir(dirp);
	
	memset(buf,0,sizeof(buf));
	fd = open(w1_path,O_RDONLY);
	if (!fd)
	{
		log_error("FILE problem%s\n",strerror(errno));
		return -2;
	}

	rv = read(fd,buf,sizeof(buf));	
	if(rv<=0)
	{
		log_error("read buf failure:%",strerror(errno));
		return -4;
	}
	str=strstr(buf,"t=");
	if(!str)
	{
		log_error("can't find string\n");
		return -5;
	}
	str += 2;
	*temp = atof(str)/1000;

	close(fd);
	return 0;

}

void * get_time()
{
    time_t      now;
    struct tm   *tt;

    now = time(NULL);
    tt= localtime(&now);
    return tt;
}
int sampling_timer(struct sn_time_interval *sti)
{
    int     flag=0;
    time_t  now;

    now=time(NULL);

    if(now>=sti->last_time+sti->interval)
    {
        sti->last_time=now;
        flag=1;
    }
    return flag;

}

